package com.example.myone.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myone.Entity.Article;
import com.example.myone.Entity.ArticleCategoryEnum;
import com.example.myone.Entity.Music;
import com.example.myone.Mapper.ArticleMapper;
import com.example.myone.Mapper.MusicMapper;
import com.example.myone.R;
import com.example.myone.Util.BytesUtils;
import com.example.myone.Util.DateTimeUtil;
import com.example.myone.Util.ImageUtils;
import com.example.myone.Util.LoginInfoUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

@RequiresApi(api = Build.VERSION_CODES.O)
public class WritingActivity extends AppCompatActivity {

    private RadioGroup radioGroup;
    private Button sumbitButton;
    private Button filePicker;
    private Button coverPicker;
    private Button musicPicker;
    private Article article;
    private Music music;
    private EditText authorEditText;
    private EditText titleEditText;
    private EditText introductionEditText;
    private TextView charCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_pager_writing);
        article = new Article(); // 初始化文章数据
        music = new Music(); // 初始化文章数据
        initView(); // 初始化视图
    }

    private void initView() {
        // 返回
        ImageView topBack = findViewById(R.id.top_back_button);
        topBack.setOnClickListener(v -> finish());
        // 标题
        TextView category = findViewById(R.id.top_title);
        category.setText("投稿");
        // 作者
        authorEditText = findViewById(R.id.author);
        // 文章标题
        titleEditText = findViewById(R.id.title);
        // 文章引言
        introductionEditText = findViewById(R.id.introduction);
        // 文章内容
        filePicker = findViewById(R.id.filePicker);
        filePicker.setOnClickListener(v -> filePickerLauncher.launch("text/plain"));
        // 文章封面
        coverPicker = findViewById(R.id.coverPicker);
        coverPicker.setOnClickListener(v -> coverPickerLauncher.launch("image/*"));
        // 音频
        musicPicker = findViewById(R.id.musicPicker);
        musicPicker.setOnClickListener(v -> musicPickerLauncher.launch("audio/*"));
        // 文章类别 按钮组选择
        radioGroup = findViewById(R.id.radioGroup);
        charCount = findViewById(R.id.charCount);
        // 添加引言监听
        introductionEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String countText = String.valueOf(s.toString().length());
                charCount.setText(countText);
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 在文本改变之前执行的操作
            }
            @Override
            public void afterTextChanged(Editable s) {
                // 在文本改变之后执行的操作
            }
        });
        // 提交按钮
        sumbitButton = findViewById(R.id.submitButton);
        sumbitButton.setOnClickListener(v -> {
            article.author = authorEditText.getText().toString();
            article.title = titleEditText.getText().toString();
            article.introduction = introductionEditText.getText().toString();
            int selectedId = radioGroup.getCheckedRadioButtonId();
            if (selectedId != -1) {
                RadioButton selectedRadioButton = findViewById(selectedId);
                article.category = selectedRadioButton.getText().toString();
            }
            article.authorId = Objects.requireNonNull(LoginInfoUtil.getUser(this)).id;
            article.createTime = DateTimeUtil.getNowStr();
            if (validateArticle(article)) {
                Article insertArticle = ArticleMapper.insertArticle(this, article);
                Log.i("==>WritingActivity：插入文章： ", "article: " + article.id);
                music.articleId = insertArticle.id;
                MusicMapper.insertMusic(this, music);
                Log.i("==>WritingActivity：插入音频： ", "music: " + music.articleId);
                Toast.makeText(this, "投稿成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    public boolean validateArticle(Article article) {
        return checkFieldNotEmpty(article.author, "作者") &&
                checkFieldNotEmpty(article.category, "类别") &&
                checkFieldNotEmpty(article.introduction, "引言") &&
                checkFieldNotEmpty(article.title, "标题") &&
                checkFieldNotEmpty(article.content, "内容") &&
                checkFieldNotEmpty(article.cover, "封面") &&
                (        // 类型不为收音机
                        !article.category.equals(ArticleCategoryEnum.RADIO.getMessage()) ||
                                // 收音机的音频不为空
                                checkFieldNotEmpty(music.bytes, "类型为<收音机>文章的音频")
                );
    }

    public boolean checkFieldNotEmpty(Object field, String fieldName) {
        if (field == null) {
            Toast.makeText(this, fieldName + "不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    // 获取用户选择的文章
    private final ActivityResultLauncher<String> filePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(), result -> {
                if (result != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    try (
                            InputStream inputStream = getContentResolver().openInputStream(result);
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    ) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            stringBuilder.append(line).append("\n");
                        }
                        filePicker.setText("上传成功");
                        article.content = stringBuilder.toString();
                        Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                        Log.i("==>WritingActivity：读取到的文章： ", article.content);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "无法打开文章txt", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    // 获取用户选择的文章封面
    private final ActivityResultLauncher<String> coverPickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(), result -> {
                if (result != null) {
                    try (
                            InputStream imageStream = getContentResolver().openInputStream(result);
                    ) {
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        // 将Bitmap对象转换为Base64字符串
                        coverPicker.setText("上传成功");
                        article.cover = ImageUtils.convertBitmapToBase64(selectedImage);
                        Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "无法加载图片", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    // 获取用户选择的音乐
    private final ActivityResultLauncher<String> musicPickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(), result -> {
                if (result != null) {
                    try (
                            InputStream musicStream = getContentResolver().openInputStream(result);
                    ) {
                        music.bytes = BytesUtils.readAllBytes(Objects.requireNonNull(musicStream));
                        musicPicker.setText("上传成功");
                        Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "无法加载音频", Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
